import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

import '../utils/permission_center_config.dart';

class ScanQrPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => _ScanQrState();

}

class _ScanQrState extends State<ScanQrPage> with WidgetsBindingObserver{
  Barcode? result;
  late QRViewController controller;

  var hasCameraEnable = false;

  var hasRequested = false;

  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    } else if (Platform.isIOS) {
      controller.resumeCamera();
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((duration) async {
      var cameraPermission = await Permission.camera.status;
      if(cameraPermission==PermissionStatus.granted||cameraPermission==PermissionStatus.limited){
        setState(() {
          hasCameraEnable = true;
          hasRequested = true;
        });
        // _initLight();
      }else{
        var info =  PermissionCenterConfig.permissionMap[Permission.camera];
        if(info['hasSet']==true){
          // print("111111");
          hasRequested = true;
        }else{
          // print("22222");
          hasRequested = false;
        }
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          if(!hasCameraEnable)
            Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CommonText('使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限',textColor: Colors.white),
                  SizedBox(height: 20,),
                  CommonText('去设置',textColor: Colors.white).onTap((){
                    _toRequestCamera();
                  })
                ],
              ),
            ),

          if(hasCameraEnable)
            QRView(
                key: qrKey,
                onQRViewCreated: _onQRViewCreated,
                overlay: QrScannerOverlayShape(
                  borderColor: Colors.red,
                  borderRadius: 10,
                  borderLength: 30,
                  borderWidth: 10,
                  cutOutSize: 300,
                )),
        ],
      )
    );
  }

  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  var num = 0;
  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {

      if(mounted&&num==0){
        Navigator.pop(context,scanData);      }
      num++;
    });
    controller.pauseCamera();
    controller.resumeCamera();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  Future<void> _toRequestCamera() async {

    if(hasRequested){
      ///跳转设置
      await openAppSettings();

    }else{
      var result = await Permission.camera.request();
      if(result==PermissionStatus.granted||result==PermissionStatus.limited){
        setState(() {
          hasCameraEnable = true;
          hasRequested = true;
        });
      }
      PermissionCenterConfig.savePermissionInit(Permission.camera);
    }
  }

}
